"use strict"

let express        = require('express')
    , favicon      = require('serve-favicon')
    , bodyParser   = require('body-parser')
    , compression  = require('compression')     //Middleware to compress request
    , cookieParser = require('cookie-parser')
    , config       = require('./config')()
    , debug        = require('debug')('http')
    , path         = require('path')
    , fs           = require('fs')
    , url          = require('url')
    , urlencode    = require('urlencode');


global.appRoot = path.resolve(__dirname);

//Connect to mongodb
let models = require('./models');

let app            = express()
    ,consoleApp    = express()
    ,identity      = express();

identity.locals.models = models;

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.set('trust proxy', config.express.trustProxy); //Because it is always befind the proxy

//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(compression());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));


app.use('/console', consoleApp);
var consoleRoutes = require('./routes/console')(consoleApp, config);

app.use('/identity', identity);
var accountRoutes = require('./routes/identity')(identity, config);

app.get('/', function(req, res, next){
  var jumpTo = "https://qy.weixin.qq.com/cgi-bin/loginpage?corp_id=wx42c1a7f89c4a258d"
                + "&redirect_uri="
                + urlencode("http://qywx-admin.auth.aivics.net?cb=http://auth.aivics.net"
                + "&client_id=56f6bff4caa511fd56c94d88")
                + "&state=1234567890&usertype=admin";

  //return res.redirect(jumpTo);
  return res.render('index', { title: 'oauth hub', jumpTo: jumpTo });
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        debug("internal server error: ", err);
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;
